<?php

namespace app\index\controller;
use think\Db;
use think\Cookie;
use app\index\model\User as UserModel;
use app\index\model\Goods as GoodsModel;
use app\index\model\Attr;
use app\index\model\Comment;
use app\index\model\Goodsimages;
use think\Controller;

class Goods extends controller
{
    //商品详情界面
    public function goods()
    {
        $id = input('get.id');
       $this->assign('id',$id);
        if (!isset($id)) {
            $id = 1;
        }
        $attr = GoodsModel::get($id);
        // 获取相同商品的颜色信息，去除重复的颜色信息
        $color = $attr->attr()->column('color');
        $color = array_unique($color);
        $this->assign('color',$color);
        // 获取相同商品的内存信息，去除重复的内存信息
        $memory = $attr->attr()->column('memory');
        $memory = array_unique($memory);
        $this->assign('memory',$memory);
        // 获取相同商品的版本信息，去除重复的版本信息
        $version = $attr->attr()->column('version');
        $version = array_unique($version);
        $this->assign('version',$version);

        // 获取商品的型号信息
        $goods = Db::name('goods')->where('id',$id)->find();
        $this->assign('goods',$goods);

        // 获取商品的描述信息
        $data['username'] = session('name');
        $this->assign('data',$data);

        // 获取商品的图片信息
        $images = Db::name('goodsimages')->where('goods_id',$id)->find();
        $this->assign('images',$images);

        //原生查询表attr数据去除goods_id相同的值保留goods_id对应的id最小的一条数据即可  获取手机的具体颜色 制式 价格 库存等属性属
        $result = Db::query ('select * from ecmall_attr where id in (select min(id) from ecmall_attr group by goods_id)'); 
        $this->assign("result",$result);
        //查询表goodsimages某款手机的图片
        $pricture = Db::name('Goodsimages')->where('image_id',1)->select();
        $this->assign("pricture",$pricture);  

        //查询品牌小米的手机前3条数据
        $xiaomi = Db::name('goods')->where('brand','小米')->order('reg_time asc')->limit(4)->select();
        $this->assign("xiaomi",$xiaomi);
        
        //查询品牌华为的手机前4条数据
        $huawei  = Db::name('goods')->where('brand','华为')->order('reg_time desc')->limit(4)->select();
        $this->assign("huawei",$huawei);

        //查询品牌oppo的手机前4条数据
        $oppo  = Db::name('goods')->where('brand','oppo')->order('reg_time desc')->limit(4)->select();
        $this->assign("oppo",$oppo);

        $list  = Db::name('comment')->where('goods_id',$id)->order('create_time desc')->select();
        $this->assign("list",$list);
        return $this->fetch();
    }
    // 添加喜欢的商品
    public function addlike()
    {
        $userid = session('id');
        $goodsid = input('get.goodsid');
        var_dump($userid);
        var_dump($goodsid);
    }
    // 商品添加购物车详情页
    public function addcart()
    {
        // 判断用户是否登陆
        if (!session('?name')) {
            $this->redirect('/index/user/login');
        }
        // 判断是否带有商品id
        if (!input('get.goodsid')) {
            $this->redirect('/');
        }
        // 将购物车商品写入数据库
        // 获取商品的规格信息(价格/颜色/内存/版本)
        $id = input('get.goodsid');
        $attr = Db::name('attr')->field('goods_id,color,memory,version,price')->where('id',$id)->find();
        $goods = Db::name('goods')->field('brand,category,abstract')->where('id',$attr['goods_id'])->find();
        $image = Db::name('goodsimages')->field('main')->where('goods_id',$attr['goods_id'])->find();
        $goodsid = Db::name('cart')->where('attr_id',$id)->find();
        // 判断是否为相同商品，相同购买数量+1
        $data = [   
                    'user_id'   =>  session('id'),
                    'username'  =>  session('name'),
                    'goodsid'   =>  $attr['goods_id'],
                    'brand'     =>  $goods['brand'],
                    'category'  =>  $goods['category'],
                    'abstract'  =>  $goods['abstract'],
                    'attr_id'   =>  input('get.goodsid'),
                    'memory'    =>  $attr['memory'],
                    'color'     =>  $attr['color'],
                    'version'   =>  $attr['version'],
                    'price'     =>  $attr['price'],
                    'count'     =>  1,
                    'image'     =>  $image['main'],
                    ];
        // 不存在相同商品，插入新商品
        if (!$goodsid == 'empty') {
            Db::name('cart')->insert($data);
        } else {
            // 存在相同商品，更新购买数量
            Db::name('cart')->where('attr_id',$id)->setInc('count');
        }
        // 获取商品的图片信息
        $images = Db::name('goodsimages')->where('goods_id',$id)->find();
        $this->assign('images',$images);
        
        $goodsinfo = Db::name('attr')->field('price,goods_id,color,memory,version')->where('id',input('get.goodsid'))->find();
        $title = Db::name('goods')->field('category,abstract')->where('id',$goodsinfo['goods_id'])->find();
        $data['username'] = session('name');
        $this->assign('goodsinfo',$goodsinfo);
        $this->assign('title',$title);
        $this->assign('data',$data);
        return $this->fetch();
    }
    // 商品结算界面
    public function balance()
    {
        $data['username'] = session('name');
        $this->assign('data',$data);
        // 获取用户购物车记录
        $cart = Db::name('cart')->field('id,goodsid,brand,category,abstract,memory,color,version,price,count,image')->where('user_id',session('id'))->where('status=0')->select();
        $this->assign('cartinfo',$cart);

        // 获取收件人地址信息
        $address = Db::name('address')->where('user_id',session('id'))->where('ismain',1)->select();
        if (!$address) {
             $this->redirect('/');
        }
        $this->assign('address',$address);
        $data['username'] = session('name');
        return $this->fetch();
    }
    // 删除购物车商品
    public function del()
    {
        Db::name('cart')->where('id',input('get.id'))->delete();
        $this->redirect('balance');
    }
    // 生成订单编号
    public function order()
    {
        // 获取收件人地址信息
        $address = Db::name('address')->where('user_id',session('id'))->where('ismain',1)->select();
        $this->assign('address',$address);

        // 获取订单信息
        $cart = Db::name('cart')->field('id,goodsid,brand,category,abstract,memory,color,version,price,count,money,image')->where('user_id',session('id'))->where('status=0')->select();
        $this->assign('cartinfo',$cart);
        foreach ($cart as $key => $value) {
            $money = $value['price'] * $value['count'];
            Db::name('cart')->where('id',$value['id'])->update(['money' => $money]);
        }
        // 计算商品总价
        $moneys = Db::name('cart')->where('status',0)->where('user_id',session('id'))->sum('money'); 
        // 查找账户余额
        $balance = Db::name('account')->field('balance')->where('user_id',session('id'))->find();

        $data['balance'] = $balance['balance'];
        $data['moneys'] = $moneys;
        $this->assign('data',$data);
        return $this->fetch();
    }
    // 订单支付界面
    public function buy()
    {
        // 获取购物车信息
        $cart = Db::name('cart')->field('id,goodsid,brand,category,abstract,memory,color,version,price,count,money,image,attr_id')->where('user_id',session('id'))->where('status=0')->select();

        // 查找账户余额
        $moneys = Db::name('cart')->where('status',0)->where('user_id',session('id'))->sum('money');
        $balance = Db::name('account')->where('user_id',session('id'))->select();
        $newBalance = $balance[0]['balance'] - $moneys;
        if ($newBalance < 0) {
            echo '账户余额不足，请返回充值';
            die;
        }
        // 减去用户账户余额、赠送积分
        $score = floor($moneys/100);
        $newScore = $balance[0]['score'] + $score;
        Db::name('account')->where('user_id',session('id'))->update(['balance' => $newBalance,'score' => $newScore]);

        // 提取商品信息简写
        $goodsinfo = $cart[0]['brand'] . $cart[0]['category'] . $cart[0]['color'] . $cart[0]['memory'] . $cart[0]['version'];
        $attrid = $cart[0]['attr_id'];
        // 获取收件人地址信息
        $address = Db::name('address')->where('user_id',session('id'))->where('ismain',1)->select();
        $this->assign('address',$address);
        $name = $address[0]['name'] . '||' . $address[0]['phone'];
        $address = $address[0]['city'] . $address[0]['address'];

        // 生成订单号(日期+随机数字)
        $ordernumber = date('ymdHis',time()) . session('id') . mt_rand(1,999);

        // 将数据写入订单列表
        foreach ($cart as $value) {
            $data = [
                        'ordernumber'   =>  $ordernumber,
                        'goods_id'      =>  $value['goodsid'],
                        'attr_id'       =>  $attrid,
                        'money'         =>  $value['price'],
                        'count'         =>  $value['count'],
                        'moneys'        =>  $moneys,
                        'user_id'       =>  session('id'),
                        'name'          =>  $name,
                        'address'       =>  $address,
                        'goodsinfo'     =>  $goodsinfo,
                        'ispay'         =>  1,
                        ];
            $order = Db::name('order')->insert($data);
        }
        // 增加销量、减少库存信息
        // foreach ($cart as $val) {
        //     var_dump($val);
        //     $stock = Db::name('attr')->where('id',$val['attr_id'])->find();
        // }
       
        // var_dump($stock);
        // die;
        
        // 循环删除购物车信息
        foreach ($cart as $key => $value) {
            $del = Db::name('cart')->where('id',$value['id'])->delete();
        }
        $account = Db::name('account')->where('user_id',session('id'))->update();
        $this->redirect('/index/user/order');

    }
    // AJAX结算界面修改数量
    public function update()
    {
        Db::name('cart')->where('id',$_POST['cartid'])->update(['count' => $_POST['count']]);
    }
    // AJAX获取商品价格
    public function getPrice()
    {   
        $id = input('post.id');
        $attr = GoodsModel::get($id);
        $price = $attr->attr()->field('price,id')->where(['memory'=>input('post.memory'),'version'=>input('post.version'),'color'=>input('post.color')])->where('stock!=0')->select();
        if (!$price) {
            $data['price'] = '无货';
            echo json_encode($data);
        } else {
            $data['id'] = $price[0]['id'];
            $data['price'] = '￥' . $price[0]['price'];
            echo json_encode($data);
        }
    }
    // 会员评论发布
    public function comment_add()
    {
         $add_attr = new Comment;
         $date = $_SERVER['REQUEST_TIME_FLOAT'];
         $add_attr->save([
                            'username' =>  input('post.username') ,            
                            'goods_id'    =>  input('post.id'),    
                            'category'   =>  input('post.category'),   
                            'discuss'  =>  input('post.discuss'),      
                            'create_time' => "$date",
                        ]);  
        $this->redirect('goods');
    }
}